package com.tma.intern;

import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;

import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.pdmodel.PDPage;
import org.pdfbox.util.PDFTextStripper;

public class PDFToImage {
	private String url = null;
	private File pdfFile = null;
	private InputStream in = null;
	public PDFToImage(String input){
		this.url = input;
	}
	public PDFToImage(File pdfFile)
	{
		this.pdfFile = pdfFile;
	}
	public PDFToImage(InputStream in){
		this.in = in;
	}
	public List<Byte[]> toByteImages() throws IOException{
		PDDocument doc = null;
		
		if (url != null) doc = PDDocument.load(url);
		else if (pdfFile != null) doc = PDDocument.load(pdfFile);
		else doc = PDDocument.load(in);
		List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
		int length = pages.size();
		List<Byte[]> listImages = new ArrayList<Byte[]>();
		for (int i = 0 ; i < length ; i++){
			PDPage singlePage = pages.get(i);
			BufferedImage buffImage = singlePage.convertToImage();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write( buffImage, "PNG", baos );
			baos.flush();
			byte[] imageInByte = baos.toByteArray();
			Byte[] byteBuff = new Byte[imageInByte.length];
			for (int j = 0 ; j < imageInByte.length ; j++){
				byteBuff[j] = (Byte) imageInByte[j];
			}
			baos.close();
			listImages.add(byteBuff);
			//return imageInByte;
		}
		return listImages;
	}
	public static void main(String[] agrs) throws IOException{
//		PDFToImage pdf = new PDFToImage("D:/intership/pdfExample/index.pdf");
//		byte[] pdfByte = pdf.toByte(0);
//		Image image = Toolkit.getDefaultToolkit().createImage(pdfByte);
//		FileOutputStream  fstream = new FileOutputStream ("D:/out.png");
//		fstream.write(pdfByte);
//		fstream.close();
//		System.out.println("done");
	}
}
